# coding=utf-8

# 说明：oss比较特殊，使用oss2包，对oss自己的endpoint进行访问
# pip install oss2

#  Usage：https://help.aliyun.com/document_detail/32027.html
#  Github：https://github.com/aliyun/aliyun-oss-python-sdk

from datetime import datetime

import oss2
from flask import jsonify

from blues.cloud import bp
from database2 import db_exec_many
from model.c_cloud import get_oss_ep_dict
from model.c_department import find_all_depart


def get_depart_buckets(access_key_id, access_key_secret, endpoint) -> list:
    auth = oss2.Auth(access_key_id, access_key_secret)
    service = oss2.Service(auth, endpoint)
    bucket_list = [b.name for b in oss2.BucketIterator(service)]
    return bucket_list


def record_oss() -> bool:
    # 1 对于专有云，只能通过部门ak sk获取oss信息
    oss_ep_dict = get_oss_ep_dict()
    depart_list = find_all_depart()
    # 初始化一个空数组，在循环中不断追加
    values_list = []
    for depart in depart_list:
        cloud_id = depart['cloud_id']
        depart_id = depart['department']
        depart_name = depart['department_name']
        # 获取一个部门下，所有bucket的列表和信息
        depart_ak = depart['access_key_id']
        depart_sk = depart['access_key_secret']
        oss_ep = oss_ep_dict[cloud_id]
        depart_buckets = get_depart_buckets(depart_ak, depart_sk, oss_ep)
        for b in depart_buckets:
            # tmp_tuple = get_bucket_info(depart_ak, depart_sk, oss_ep, b)
            auth = oss2.Auth(depart_ak, depart_sk)
            bucket = oss2.Bucket(auth, oss_ep, b)
            b_info = bucket.get_bucket_info()
            b_stat = bucket.get_bucket_stat()
            b_cap = bucket.get_bucket_storage_capacity()
            tmp_tuple = (
                b_info.name, cloud_id, depart_id, depart_name, b_info.acl.grant, b_cap.storage_capacity,
                b_stat.storage_size_in_bytes, b_info.creation_date, datetime.now()
            )
            values_list.append(tmp_tuple)
            # print(tmp_tuple)
    # 2 操作sql批量插入
    table = 'c_oss_info'
    fields = "bucket,cloud_id,depart_id,depart_name,`grant`,capacity,size_in_bytes,creation_time,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route("/api/v1/cloud/record_oss", methods=['POST'])
def record_oss_api():
    success = record_oss()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
